package com.feiyumall.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.feiyu.common.utils.R;
import com.feiyumall.account.dao.BuyerDao;
import com.feiyumall.account.dao.LogisticsStaffDao;
import com.feiyumall.account.dao.ShopDao;
import com.feiyumall.account.dao.UserDao;
import com.feiyumall.account.dto.loginDto;
import com.feiyumall.account.dto.registerDto;
import com.feiyumall.account.entity.BuyerEntity;
import com.feiyumall.account.entity.LogisticsStaffEntity;
import com.feiyumall.account.entity.ShopEntity;
import com.feiyumall.account.entity.UserEntity;
import com.feiyumall.account.entity.redis.accountInfoEntity;
import com.feiyumall.account.service.loginService;
import com.feiyumall.account.service.tokenService;
import com.feiyumall.account.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Doate
 * @Date: Created in 2021/4/10 14:36
 * @Description:
 */
@Service
public class loginServiceImpl implements loginService {

    @Resource
    UserDao userDao;

    @Resource
    BuyerDao buyerDao;

    @Resource
    ShopDao shopDao;

    @Resource
    LogisticsStaffDao logisticsStaffDao;

    @Resource
    tokenService tokenService;

    @Override
    public R logining(HttpServletResponse response, loginDto dto) {

        QueryWrapper<UserEntity> userEntityQueryWrapper = new QueryWrapper<>();
        userEntityQueryWrapper.eq("user_name", dto.getUserName())
                .eq("del_flag", 0);

        List<UserEntity> userInfoList = userDao.selectList(userEntityQueryWrapper);

        //判断账号是否存在
        if (userInfoList.isEmpty()) {
            return R.error(4013, "账号不存在").put("data", null);
        }

        //判断密码是否正确
        UserEntity userInfo = userInfoList.get(0);
        if (!dto.getUserPwd().equals(userInfo.getUserPwd())) {
            return R.error(4014, "密码错误").put("data", null);
        }

        //判断用户权限是否满足
        switch (dto.getPlatform()) {
            case 0:
                if (userInfo.getUserPower() < 10 && dto.getPlatform() == 0) {
                    break;
                }
            case 1:
                if (userInfo.getUserPower() >= 11 && userInfo.getUserPower() <= 13 && dto.getPlatform() == 1) {
                    break;
                }

            case 2:
                if (userInfo.getUserPower() == 10 && dto.getPlatform() == 2) {
                    break;
                }

            default:
                return R.error(4015, "无权登录").put("data", null);
        }

        //账号可以正常登录的情况下
        accountInfoEntity info = new accountInfoEntity(userInfo);
        response.setHeader("token", tokenService.addToken(info));

        //当账户为买家与卖家时，获取他们的对应逻辑id

        int logicId = -1;
        int power = info.getUserPower();
        if (power == 10) {
            QueryWrapper<BuyerEntity> con = new QueryWrapper<>();
            con.eq("user_id", info.getUserId());
            logicId = buyerDao.selectOne(con).getBuyerId();
        }
        if (power > 10 && power < 14) {
            QueryWrapper<ShopEntity> con = new QueryWrapper<>();
            con.eq("user_id", info.getUserId());
            logicId = shopDao.selectOne(con).getShopId();
        }

        //封装返回信息
        Map<String, Object> data = new HashMap<>();
        data.put("userId", info.getUserId());
        data.put("userName", info.getUserName());
        data.put("userPower", info.getUserPower());
        data.put("logicId", logicId);

        return R.ok().put("data", data);
    }

    @Override
    public accountInfoEntity loginCheck(String token) {

        accountInfoEntity info;

        if (tokenService.checkToken(token)) {
            info = tokenService.getAccount(token);

            info.setIsTrue(true);
            return info;
        } else {
            info = new accountInfoEntity();
            info.setIsTrue(false);
            return info;

        }


    }

    @Override
    public R register(registerDto dto) {

        //检查用户名是否重复
        QueryWrapper<UserEntity> con1 = new QueryWrapper<>();
        con1.eq("user_name", dto.getUserName());
        if (!userDao.selectList(con1).isEmpty()) {
            return R.error(4011, "用户名重复");
        }

//        创建用户账号信息
        UserEntity userEntity = setUserInfo(dto);
        userDao.insert(userEntity);

//        根据用户账号类型，分别创建各自表的基础信息
        int power = dto.getUserPower();

        if (power == 10) {
            BuyerEntity entity = new BuyerEntity();

            entity.setUserId(userEntity.getUserId());
            entity.setBuyerName(dto.getNickName());

            buyerDao.insert(entity);
        }

        if (power > 10 && power < 14) {
            ShopEntity entity = new ShopEntity();

            entity.setUserId(userEntity.getUserId());
            entity.setShopType(dto.getShopType());

            shopDao.insert(entity);
        }

        if (power == 20) {
            LogisticsStaffEntity entity = new LogisticsStaffEntity();

            entity.setUserId(userEntity.getUserId());
            entity.setLogisticsPlateform(dto.getPlateformName());
            entity.setLogisticsPlateformNo(dto.getPlateformNo());

            logisticsStaffDao.insert(entity);
        }


        return R.ok();
    }

    public UserEntity setUserInfo(registerDto dto) {

        UserEntity userEntity = new UserEntity();

        userEntity.setUserName(dto.getUserName());
        userEntity.setUserBirth(dto.getUserBirth());
        userEntity.setUserIdent(dto.getResidentId());
        userEntity.setUserPower(dto.getUserPower());
        userEntity.setUserTel(dto.getUserTel());
        userEntity.setUserPwd(dto.getUserPwd());

        return userEntity;
    }

    @Override
    public R updateUser(registerDto dto, int userId) {

        UserEntity entity = setUserInfo(dto);

        UpdateWrapper<UserEntity> con = new UpdateWrapper<>();
        con.eq("user_id", userId);

        userDao.update(entity, con);

        return R.ok();
    }


}
